package org.example.ThreadTest;

/**
 * ClassName: ProdcuerConsumerTest
 * Description:
 *
 * @Author HTAO
 * @Create 2023/11/11 13:17
 */
class Resorce{
    int number = 0;
    //增加产品
    public synchronized void addProduct(){
        if(number >= 20){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"生产了第"+number+"产品");
        notify();
    }
    //减少产品
    public synchronized void minusProduct(){
        if(number <=0){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(Thread.currentThread().getName()+"消费了第"+number+"产品");
        number--;
        notify();
    }
}
class Producer extends Thread{
    private Resorce resorce;

    public Producer(Resorce resorce) {
        this.resorce = resorce;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("生产者开始生产。。。");
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            resorce.addProduct();

        }
    }
}
class Consumer extends Thread{
    private Resorce resorce;

    public Consumer(Resorce resorce) {
        this.resorce = resorce;
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("消费者开始消费。。。");
            resorce.minusProduct();
        }
    }

}
public class ProdcuerConsumerTest {
    public static void main(String[] args) {
        Resorce a =new Resorce();
        Producer p = new Producer(a);
        Consumer c = new Consumer(a);
        Consumer c2 = new Consumer(a);
        p.setName("生产者");
        c.setName("消费者1");
        c2.setName("消费者2");
        p.start();
        c.start();
        c2.start();
    }

}
